#!/usr/bin/env bash

set -e

export AWS_DEFAULT_REGION="cn-northwest-1"
export AWS="$(which aws) --no-cli-pager --no-paginate --region ${AWS_DEFAULT_REGION} --color off"

if [ $# -lt 2 ]; then
	echo "Usage: $0 <code> <version>"

	GROUP_ID="com.lakeworks"
	ARTIFACT_ID="lakeworks-admin"

	GROUP_PATH=$(echo "${GROUP_ID}" | /usr/bin/sed 's/\./\//g')

	REPO_BUCKET="repo.dajingxiapp.com"
	REPO_URL="s3://${REPO_BUCKET}/releases/${GROUP_PATH}"

	${AWS} s3 cp ${REPO_URL}/${ARTIFACT_ID}/maven-metadata.xml - | xmllint --xpath '/metadata/versioning/versions/version/text()' -
	exit
fi

APPLICATION="lake"
MODULE=$1
PROFILE="master"
VERSION=$2

AUTO_SCALING_GROUP="${APPLICATION}-${MODULE}-${PROFILE}"

#LT_ID="lt-0a0de3916921f3233"
#SUBNETS="subnet-0497d7a96be8388eb,subnet-060bbec59ed2f1d08,subnet-0b15c4a2e43a8e10d"
#TARGET_GROUP_ARN=$($AWS --output text elbv2 describe-target-groups --names "${APPLICATION}-${MODULE}-${PROFILE}" --query 'TargetGroups[0].TargetGroupArn')
#
#${AWS} autoscaling create-auto-scaling-group \
#	--auto-scaling-group-name ${AUTO_SCALING_GROUP}\
#	--launch-template LaunchTemplateId=${LT_ID} \
#	--min-size 1 \
#	--max-size 2 \
#	--desired-capacity 1 \
#	--health-check-type ELB \
#	--health-check-grace-period 30 \
#	--vpc-zone-identifier ${SUBNETS} \
#	--termination-policies OldestInstance \
#	--no-new-instances-protected-from-scale-in \
#	--default-instance-warmup 30 \
#	--traffic-sources Identifier=${TARGET_GROUP_ARN},Type=elbv2 \
#	--instance-maintenance-policy MinHealthyPercentage=100,MaxHealthyPercentage=200 \
#	--tags \
#		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Application,Value=${APPLICATION},PropagateAtLaunch=True \
#		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Module,Value=${MODULE},PropagateAtLaunch=True \
#		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Profile,Value=${PROFILE},PropagateAtLaunch=True \
#		ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Version,Value=${VERSION},PropagateAtLaunch=True
#
#exit $?

${AWS} autoscaling create-or-update-tags \
	--tags ResourceId=${AUTO_SCALING_GROUP},ResourceType=auto-scaling-group,Key=Version,Value=${VERSION},PropagateAtLaunch=true
${AWS} autoscaling start-instance-refresh \
	--auto-scaling-group-name ${AUTO_SCALING_GROUP} \
	--preferences SkipMatching=false,ScaleInProtectedInstances=Refresh,StandbyInstances=Terminate,MinHealthyPercentage=100,MaxHealthyPercentage=200,CheckpointPercentages=50,100,CheckpointDelay=10
